/*
 *  realBall.cpp
 *  opencvExample
 *
 *  Created by 真鍋 大度 on 11/03/02.
 *  Copyright 2011 Rhizomatiks. All rights reserved.
 *
 */



#include "realBall.h"

void realBall::setSpeed(float _speed){
	speed = _speed;
}


void realBall::passingCheckPoint(int _checkID, float _speed){
	checkPointID = _checkID;
	speed = _speed;
	y = checkPointID;
	start();
	if (y==0) {
		bActiveAnalysedByCheckPoint = false;
	}else {
		bActiveAnalysedByCheckPoint = true;
	}

//	start();
}

void realBall::update(unsigned char * _colorpixels)
{
	currentColorPixels = _colorpixels;	
}

void realBall::start(){
	startThread(true, false);   // blocking, verbose
	bActive = true;
}

void realBall::stop(){
	stopThread();
	bActive = false;
}

//--------------------------
void realBall::threadedFunction(){
	
	while( isThreadRunning() != 0 ){
		if( lock() ){
			//-----------------------------threaded function----------------------------//
			x = y % 2 == 0 ? w - 1 - countThread : countThread;			
			col.r = currentColorPixels[(x + y * w) * 3 + 0];
			col.g = currentColorPixels[(x + y * w) * 3 + 1];
			col.b = currentColorPixels[(x + y * w) * 3 + 2];	
			float grey = (col.r + col.g + col.b) / 3.0f / 255.0f;
			pos.set(x, y);
			
			ofxDaito::bang("/vol", myID, pos.x, pos.y, grey);
			if (grey==1.0) {
				ofxDaito::bang("/volpeak", myID, pos.x, pos.y, 1);
			}
			//-----------------------------threaded function----------------------------//			
			
			//-----------------------------serial------------------------------//
			//これでx, yはセット終了。
			countThread++;
			if(countThread > 199) {
			ofxDaito::bang("/vol", myID, pos.x, pos.y, 0);
				countThread = 0;
				speed = 0;
				stop();
			}
			unlock();
			ofSleepMillis(speed);
		}
	}
}

ofVec2f & realBall::getPos(){	
	return pos;
}

bool realBall::amIActive(){
	return bActive;
}

bool realBall::amIActiveAnalysedByCheckPoint(){
	return bActiveAnalysedByCheckPoint;
}

//--------------------------
void realBall::draw(){
	
	string str = "I am a slowly increasing thread. \nmy current countThread is: ";
	
	if( lock() ){
		str += ofToString(countThread);
		unlock();
	}else{
		str = "can't lock!\neither an error\nor the thread has stopped";
	}
	ofDrawBitmapString(str, 50, 56);
}
